/**
 * 下载模板
 */
import { Loading } from 'element-ui'
import axios from '@tapui/utils/request'

export const mixin_download_template = {
  methods: {
    // 下载导入模板
    downloadTemplate(templateName, fileName) {
      axios({
        url: this.url.downloadTemplate,
        method: 'post',
        data: { param: this.model, templateName: templateName, fileName: fileName },
        responseType: 'blob'
      }).then((response) => {
        this.doDownload(response, fileName)
      })
    },
    doDownload(response, fileName) {
      let loadingInstance = Loading.service({ fullscreen: true })
      var blob = new Blob([response], { type: 'application/octet-stream;charset=utf-8' })
      var tempObjectUrl = window.URL.createObjectURL(blob)
      var aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.download = fileName
      aLink.href = tempObjectUrl
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink)
      window.URL.revokeObjectURL(tempObjectUrl)
      this.$nextTick(() => {
        // 以服务的方式调用的 Loading 需要异步关闭
        loadingInstance.close()
      })
    }
  }
}
